<?php
/**
 * Created by PhpStorm.
 * User: l
 * Date: 2018/10/25
 * Time: 17:40
 */
use app\assets\AppAsset;
use app\common\CommonHelper;

$base = Yii::$app->request->baseUrl;
AppAsset::addCss($this,$base . '/app/css/dynamic-detail.css?V=0.0.9');

AppAsset::addCss($this,$base . '/app/css/skin/jedate.css');
AppAsset::addScript($this,$base . '/app/js/jedate.js');

AppAsset::addCss($this,$base . '/css/jquery.Jcrop.css');
AppAsset::addScript($this,$base . '/js/jquery.Jcrop.min.js');

AppAsset::addCss($this,$base . '/css/multi-file-upload.css');

AppAsset::addCss($this,$base . '/app/css/vest-list.css');



$model = new CommonHelper();
$baseUrlHead  = $model->getIp();

$barId = isset($bar['bar_id'])?$bar['bar_id']:-1;
$barName = isset($bar['bar_name'])?$bar['bar_name']:"";
?>
<div class="detail-container" style="width: 74rem">
    <p class="top-title">动态详情</p>

    <p class="item-title"><span class="necessary-note">*</span>发布者</p>

    <div class="dropdown" style="font-size: 1.3rem">
        <span id="dynamicUserId" class="user-select">
            未选择马甲
        </span>

        <span class="update-vest" onclick="showVestDialog('dynamicUserId')">更换</span>
    </div>

    <p class="item-title">标题</p>
    <input id="dynamicTitle" class="input-row" placeholder="请输入" maxlength="20">

    <p class="item-title"><span class="necessary-note">*</span>正文</p>
    <textarea id="dynamicContent" class="textarea-row" placeholder="请输入" maxlength="500"></textarea>

    <p class="item-title"><span class="necessary-note">*</span>发布时间</p>
    <p class="datep" id="releaseTime" style="float: none;">
        <img src="<?=$base?>/app/images/new/rc_icon_date.png" class="date-icon">
        <input class="datainp" id="datebut" type="text" placeholder="请选择"  readonly>
    </p>

    <p class="item-title"><span class="necessary-note">*</span>所在地</p>
    <select id="cityID">
        <option value="179">杭州市</option>
        <?php for($index=0;$index<count($cities);$index++){?>
            <option value="<?= $cities[$index]['city_code']?>"><?= $cities[$index]['city_name']?></option>
        <?php }?>
    </select>  

    <p class="item-title">商家</p>
    <div class="dropdown">
        <button type="button" class="btn dropdown-toggle" id="dropdownMenu1" bar-id="-1"
                data-toggle="dropdown">
            未选择
            <span class="caret"></span>
        </button>
        <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
            <?php for($index=0;$index<count($bars);$index++){?>
                <li role="presentation" >
                    <a role="menuitem" tabindex="-1" href="javascript:chooseBar('<?= $bars[$index]['bar_id']?>','<?= $bars[$index]['bar_name']?>')"><?= $bars[$index]['bar_name']?></a>
                </li>
            <?php }?>
        </ul>
    </div>
    <script type="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>

    <p class="item-title"><span class="necessary-note">*</span>图片（最多9张）</p>
    <input type="file" accept="image/jpg,image/jpeg,image/png" id="upload-file2" name="upload-file2" onchange="" multiple="multiple" style="display: none">
    <div class="image-container">
        <div id="imageChoose" class="image-item" onclick="showPic()">
            <img class="image-choose" src="<?= $base?>/app/images/dynamic/default-logo.png">
        </div>
    </div>

    <div class="clear"></div>

    <div class="button-div" style="margin-top: 1.67rem">保存</div>
</div>                              

<div id="chooseUser" class="dialog-operate" hidden="hidden">
    <div class="user-item-container">
        <p class="dialog-title">选择马甲<img style="float: right;margin-top: 6px;cursor: pointer" src="<?= $base?>/app/images/close.png" onclick="hideVestDialog()"></p>
        <div class="clear"></div>
        <div class="divider-line"></div>
        <div class="vest-box">
        </div>

        <div class="clear"></div>
        <table id="table3" hidden="hidden"></table>
    </div>

</div>

<div class="upImg" hidden="hidden">
    <div class="choose-pic" id="choose-pic">
        <div style="width: 100%">
            <label>请选择图</label>
            <img class="myClose" src="<?= $base?>/app/images/close.png">
        </div>
        <button class="select-img">选择图片</button>
        <div class="pic-area">
            <div id="showimg" style="">
                <ul id="showui" style="width: 561px; height: 340px;">
                </ul>
                
                <div id="showinput">
                </div>
            </div>
            <!-- <img class="pic-area-img" id="pic-area-img" > -->
        </div>
        <div>
            <button id="submit" class="upload-img">保存</button>  
        </div>
    </div>
</div>

<script>

    var baseUrlHead = '<?= $baseUrlHead?>';
    var barId = '<?= $barId?>';
    var barName = '<?= $barName?>';

    function chooseBar(bar_id,bar_name){
        $("#dropdownMenu1").text(bar_name);
        $("#dropdownMenu1").attr("bar-id",bar_id);
    }

    //初始化表格设置
    $('#table3').bootstrapTable({

//        height: 525,//高度
        toolbar: '#toolbar',        //工具按钮用哪个容器
        clickToSelect: true,//点击行即可选中单选/复选框
        singleSelect: false,//复选框只能选择一条记录
        search: false,//是否显示右上角的搜索框
        striped: true,      //是否显示行间隔色
        cache: false,            //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sidePagination: "server", //服务端处理分页
        pagination: true,     //是否显示分页（*）
        sortable: false,           //是否启用排序
        sortOrder: "asc",          //排序方式
        method: 'GET',      //请求方式（*）
        pageNumber:1,      //初始化加载第一页，默认第一页
        pageSize: 18,      //每页的记录行数（*）
//        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        cardView: false,          //是否显示详细视图
        onPageChange:function(){$('#table3').bootstrapTable('hideLoading');},//隐藏数据加载中
        uniqueId:'user_id',
        url:'vest-data',
        responseHandler:dataUserProcess,

        columns: [{
            field: '',
            align: 'center',
            valign: 'middle',
            title: '用户列表',
            formatter:function(value,row,index) {
                $('.fixed-table-body').eq(0).css('height','0px');
                $('.pull-left').eq(0).hide(); //隐藏数据加载中
            }
        }]
    });
    $('.fixed-table-container').eq(0).css('border','none');
    $('#table3').bootstrapTable('hideLoading'); //隐藏数据加载中

    function dataUserProcess(res){
        var result = res;

        $(".vest-box").empty();
        var html = "";
        var datas = result.rows;
        for(var index = 0 ; index < datas.length; index ++){
            var data = datas[index];
            html +='<div class="vest-item">'+
            '<img class="vest-avatar" src="'+data.user_avatar+'">'+
            '<span class="vest-message">'+getCommentUserMessage(data.user_nickname,data.user_sex,data.city_name)+'</span>'+
            '<span class="vest-choose" userid="'+data.user_id+'" usertoken="'+data.token+'" username="'+data.user_nickname+'" onclick="chooseVestInsert(this)">选择</span>'+
            '</div>';
        }
        $(".vest-box").append(html);

        return {
            'rows':result.rows,
            'total':result.total
        }

    }

    var typeUserView = "dynamicUserId";
    function showVestDialog(viewId){
        typeUserView = viewId;
        $("#chooseUser").show();
    }

    function chooseVestInsert(view){
        $("#"+typeUserView).text($(view).attr("username"));
        $("#"+typeUserView).attr("userid",$(view).attr("userid"));
        $("#"+typeUserView).attr("usertoken",$(view).attr("usertoken"));
        hideVestDialog();
    }

    function hideVestDialog(){
        $("#chooseUser").hide();
    }

    function getCommentUserMessage(name,sex,area){
        var userString = "";
        userString += name;

        if(sex == 0)
            userString +="（女，";
        else
            userString +="（男，";

        userString +=area + "）";

        return userString;
    }

    var dynamicCreateController = {
        dynamicCreateApi : baseUrlHead + 'Hotcity/v1/dynamics',
        dynamicCreateFunc : function(){

            var userId = $("#dynamicUserId").attr("userid");
            var userToken = $("#dynamicUserId").attr("usertoken");

            if(userId == undefined){
                alert("请选择马甲用户");
                return;
            }

            var content = $("#dynamicContent").val().replace(/[&\|\\\*^%$#@\-]/g,"");
            if(content.length == 0){
                alert("请输入动态内容");
                return;
            }

            if(content.length < 15){
                alert("动态内容需最少15字");
                return;
            }

            var cityCode = $("#cityID").val();

            var param = {
                user_id:userId,
                token:userToken,
                dynamic_content:content,
                city_code : cityCode
            };

            var barId = $("#dropdownMenu1").attr("bar-id");

            if(barId != -1)
                param.bar_id = barId;

            var title = $("#dynamicTitle").val().replace(/[&\|\\\*^%$#@\-]/g,"");
            if(title.length != 0)
                param.dynamic_title = title;

            if($(".image-value").length > 0)
                param.photos = getImageValue();

            $('.loading-area').show();
            sendAjax(this.dynamicCreateApi,"POST",param,null,function(res){
                $('.loading-area').hide();
                if(res.code != 0){
                    // 将json格式数据转换成数组格式
                    var result = JSON.parse(res);
                    var time = $('#datebut').val();

                    if (time && time != undefined){
                        var dynamicApi = 'dynamic-time';

                        var param = {
                            dynamic_id : result.data.dynamic_id,
                            gmt_publish : time
                        };

                        sendAjax(dynamicApi,"POST",param,null,function(res){
                            var result = JSON.parse(res);
                            if (result.code == 0) {
                                location.href = "dynamic-list";
                            } else {
                                alert('更新失败');
                            }
                        });

                    } else {
                        location.href = "dynamic-list";
                    }
                }else
                    alert(res.msg);
            });
        }
    };

    

    $(function(){
        //选择图片点击事件
        $(".myClose").click(function(){
            closePic();
        });
        $(".select-img").click(function(){
            upload(this);
        });
        //选择图片结束
        $(".button-div").click(function(){
            dynamicCreateController.dynamicCreateFunc();
        });

        if(barId != -1)
            chooseBar(barId,barName);
    });

    var photoMax = 9;
    //点击图片来选择上传的图片
    function upload(button){
//        $(button).css('background-color','#77778F').css('color','white');
        var intputId = 'upload-file2';
        document.getElementById(intputId).click();
    }

    function showPic(){
        $('.upImg').show();
    }

    function closePic(){
        $('.upImg').hide();
        $('.pic-area').empty();
        if (!$('.pic-area img').length){
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img">');
        }
        $('.upload').css('background-color','white').css('color','#A8A8A8');
        $('.select-img').css('background-color','white').css('color','#A8A8A8');
        //清除input file 的value,可以触发下次的onchange;
        $('#upload-file2').val('');

        $('.upload-img').css('background','white').prop('disabled',false);
    }

    function deleteImage(view){
        $(view).parent().remove();
        if($(".image-value").length < photoMax)
            $("#imageChoose").show();
    }

    function getImageValue(){
        var imageString = "";
        $(".image-value").each(function() {
            imageString +=$(this).attr("src") + ";";
        });
        var reg=/;$/gi;
        return imageString.replace(reg,"");
    } 

    // 多图片上传
    window.onload = function() {
        var input = document.getElementById("upload-file2");
        var showui = document.getElementById("showui");
        var result;
        var dataArr = []; // 储存所选图片的结果(文件名和base64数据)
        var fd; //FormData方式发送请求
        var showinput = document.getElementById("showinput");
        var oSubmit = document.getElementById("submit");
        var dateli, dateinput;
        if(typeof FileReader === 'undefined') {
            alert("抱歉，你的浏览器不支持 FileReader");
            input.setAttribute('disabled', 'disabled');
        } else {
            input.addEventListener('change', readFile, false);
        }

        function readFile() {
            fd = new FormData();
            var iLen = this.files.length;
            var index = 0;
            var currentReViewImgIndex = 0;
            for(var i = 0; i < iLen; i++) {
                if(!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)) {　　 //判断上传文件格式
                    return alert("上传的图片格式不正确，请重新选择");
                }
                var reader = new FileReader();
                reader.index = i;
                fd.append(i, this.files[i]);
                reader.readAsDataURL(this.files[i]); //转成base64
                reader.fileName = this.files[i].name;
                reader.files = this.files[i];
                reader.onload = function(e) {
                    var imgMsg = {
                        name: this.fileName, //获取文件名
                        base64: this.result, //reader.readAsDataURL方法执行完后，base64数据储存在reader.result里
                        files: this.files
                    }
                    dataArr.push(imgMsg);
                    for(var j = 0; j < dataArr.length; j++) {
                        currentReViewImgIndex = j
                    }
                    result = '<div class="showdiv"><img class="left" src="<?= $base?>/app/images/img/Arrow_left.svg" /><img class="center" src="<?= $base?>/app/images/img/delete.svg" /><img class="right" src="<?= $base?>/app/images/img/Arrow_right.svg" /></div><img id="srcimgid' + currentReViewImgIndex + '" class="showimg" src="' + this.result + '" width="150px" height="150px" />';
                    var li = document.createElement('li');

                    li.innerHTML = result;
                    showui.appendChild(li);
                    index++;
                }
            }
        }

        function onclickimg() {
            var dataArrlist = dataArr.length;
            var lilength = document.querySelectorAll('ul#showui li');

    //      console.log(lilength)
            for(var i = 0; i < lilength.length; i++) {

                lilength[i].getElementsByTagName('img')[0].onclick = function(num) {
                    return function() {
                        if(num == 0) {} else {
                            var list = 0;
                            for(var j = 0; j < dataArr.length; j++) {
                                list = j
                            }
                            var up = num - 1;
                            dataArr.splice(up, 0, dataArr[num]);
                            dataArr.splice(num + 1, 1)

                            var lists = $("ul#showui li").length;
                            for(var j = 0; j < lists; j++) {
                                var usid = $("ul#showui li")[j].getElementsByTagName('img')[3];
                                $("#" + usid.id + "").attr("src", dataArr[j].base64)
                            }
                         // console.log(dataArr);
                        }
                    }
                }(i)

                //删除图标
                lilength[i].getElementsByTagName('img')[1].onclick = function(num) {
                    return function() {
                        if(dataArr.length == 0) {
                            dataArr = "";
                            $("#showui").html("")
                        } else {
                            $("#showui li:eq(" + num + ")").remove()
                            dataArr.splice(num, 1)
                        }
                    }
                }(i)

                //右箭头图标
                lilength[i].getElementsByTagName('img')[2].onclick = function(num) {
                    return function() {
                        var list = 0;
                        for(var j = 0; j < dataArr.length; j++) {
                            list = j
                        }
                        var datalist = list + 1;
                        dataArr.splice(datalist, 0, dataArr[num]);
                        dataArr.splice(num, 1)

                        var lists = $("ul#showui li").length;
                        for(var j = 0; j < lists; j++) {
                            var usid = $("ul#showui li")[j].getElementsByTagName('img')[3];
                            $("#" + usid.id + "").attr("src", dataArr[j].base64)
                        }
                    }
                }(i)

            }
        }

        showui.addEventListener("click", function() {
            //监听每次加载的储存所选图片数据，更改数组渲染
            onclickimg();
        })

        function send() {
            if (dataArr.length > 0) {
                for(var j = 0; j < dataArr.length; j++) {
                    var limit = 8 * 1024 * 1024;
                    var filetype = ['jpg','jpeg','png','gif'];
                    // console.log(dataArr[j].name)
                    //判断文件格式是否是图片 如果不是图片则返回false
                    var index = dataArr[j].name.lastIndexOf('.');

                    var fname = [dataArr[j].name.substring(0,index),dataArr[j].name.substring(index+1)];
                    if(filetype.indexOf(fname[1].toLowerCase()) == -1){
                        alert('文件格式不支持');
                        return;
                    }

                    //开始上传之前，预览图片
                   // $('#img').attr('src',pic);
                    //使用ajax 利用post方式提交数据

                    if(dataArr[j].files.size > limit){
                        alert("上传照片不得大于8M");
                        return;
                    }
                    $('.loading-area').show();
                    $('#submit').css('background','#CCCCCC').prop('disabled',true);

                    var formFile = new FormData();
                    formFile.append("file", dataArr[j].files); //加入文件对象

                    $.ajax({
                       url: "img-upload",
                       data: formFile,
                       type: "post",
                       dataType: "json",
                       cache: false,//上传文件无需缓存
                       processData: false,//用于对data参数进行序列化处理 这里必须false
                       contentType: false, //必须
                       success: function (result) {
                           // var data = eval('('+result+')');

                           if(result.code == 1){
                               $('.loading-area').hide();
                               alert('上传失败');
                           }else if(result.code == 0){
                               var imgHtml = '<div class="image-item">'+
                                   '<img class="image-delete" style="cursor: pointer" src="<?= $base?>/app/images/dynamic/rc_icon_seduce_dynamic_found_picture_close.png" onclick="deleteImage(this)">'+
                                   '<img class="image-value" src="'+result.imgSrc+'">'+
                                   '</div>';

                               $(".image-container").append(imgHtml);

                               if($(".image-value").length == photoMax)
                                   $("#imageChoose").hide();

                               $('.loading-area').hide();
                               closePic();
                               $("ul#showui").html("");
                           }else if(result.code == 2){
                               var size = parseInt(parseInt(data.size)/1000);
                               if (size>1000)
                                   size = parseInt(size/1000) + 'M';
                               else
                                   size += 'KB';
                               var msg = data.msg + ',当前图片尺寸为:' + size;
                               $('.loading-area').hide();
                               alert(msg);
                           }
                       },
                       error:function(XMLHttpRequest, textStatus, errorThrown){
                           $("#loadingBox").hide();
                           alert(result.msg);
                       }
                   });
//                     .fail(function(xhr,status,error){
// //                    console.log(xhr,status,error)
//                         $('.loading-area').hide();
//                         alert('上传失败');
//                     });
                }
            }else{
                alert('请选择图片');
            }
        }

        oSubmit.onclick = function() {
            if(!dataArr.length) {

                return alert('请先选择文件');
            }
            send();
        }

        var start = {
            format: 'YYYY-MM-DD hh:mm:ss',
            minDate: '2016-08-08 12:00:00', //设定最小日期为当前日期
            skinCell:"jedateblue",
            festival:false,
            isTime:true,
            isToday:false,
            isClear:false,
            maxDate: '2099-06-30 12:00:00'
        };
        $.jeDate('#datebut',start);
    }
</script>
